<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="所属学校ID" prop="schoolId">
        <el-input
          v-model="queryParams.schoolId"
          placeholder="请输入所属学校ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属机房" prop="labId">
        <el-select
            v-model="queryParams.labId"
            placeholder="请选择所属机房"
            clearable
            style="width: 150px"
        >
          <el-option
              v-for="lab in labList"
              :key="lab.labId"
              :label="`${lab.labName} (ID:${lab.labId})`"
              :value="lab.labId"
          >
            <span style="float: left">{{ lab.labName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">ID:{{ lab.labId }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户端名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户端名称 (如：PC - 01)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="IP地址" prop="ipAddress">
        <el-input
          v-model="queryParams.ipAddress"
          placeholder="请输入IP地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="MAC地址" prop="macAddress">
        <el-input
          v-model="queryParams.macAddress"
          placeholder="请输入MAC地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后心跳时间" prop="lastHeartbeat">
        <el-date-picker clearable
          v-model="queryParams.lastHeartbeat"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择最后心跳时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="注册时间" prop="registrationTime">
        <el-date-picker clearable
          v-model="queryParams.registrationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择注册时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['schoolmanage:clients:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['schoolmanage:clients:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['schoolmanage:clients:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['schoolmanage:clients:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clientsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户端ID" align="center" prop="clientId" />
      <el-table-column label="所属学校ID" align="center" prop="schoolId" />
      <el-table-column label="所属机房" align="center" prop="labName">
        <template #default="scope">
          {{ scope.row.labName || '未分配机房' }}  <!-- 显示labName，如果为空则显示"未分配机房" -->
        </template>
      </el-table-column>
      <el-table-column label="客户端名称" align="center" prop="clientName" />
      <el-table-column label="IP地址" align="center" prop="ipAddress" />
      <el-table-column label="MAC地址" align="center" prop="macAddress" />
<!--      'online','offline','in_use','maintenance'-->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <template v-if="scope.row.status === 'online'">
           <el-text type="success">
             <el-icon><Check /></el-icon> 在线
           </el-text>
          </template>
          <template v-else-if="scope.row.status === 'offline'">
            <el-text type="info">
              <el-icon><Close /></el-icon> 离线
            </el-text>
          </template>
          <template v-else-if="scope.row.status === 'maintenance'">
            <el-text type="danger">
              <span>🔧</span> 维护中
            </el-text>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="最后心跳时间" align="center" prop="lastHeartbeat" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastHeartbeat, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="registrationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.registrationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['schoolmanage:clients:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['schoolmanage:clients:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户端管理对话框 -->
    <el-dialog :title="title" v-model="open" width="520px" append-to-body>
      <el-form ref="clientsRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入所属学校ID" disabled/>
        </el-form-item>
        <el-form-item label="所属机房" prop="labId" required>
          <el-select
              v-model="form.labId"
              placeholder="请选择所属机房"
          >
            <el-option
                v-for="lab in labList"
                :key="lab.labId"
                :label="`${lab.labName} (ID:${lab.labId})`"
                :value="lab.labId"
            >
              <span style="float: left">{{ lab.labName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">ID:{{ lab.labId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户端名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户端名称 (如：PC - 01)" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
        </el-form-item>
        <!--      'online','offline','in_use','maintenance'-->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="online" value="online"></el-option>
            <el-option label="offline" value="offline"></el-option>
            <el-option label="in_use" value="in_use"></el-option>
            <el-option label="maintenance" value="maintenance"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最后心跳时间" prop="lastHeartbeat">
          <el-date-picker clearable
            v-model="form.lastHeartbeat"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后心跳时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="注册时间" prop="registrationTime">
          <el-date-picker clearable
            v-model="form.registrationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Clients">
import { listClients, getClients, delClients, addClients, updateClients } from "@/api/schoolmanage/clients"
import { listLabs } from "@/api/schoolmanage/labs";
import { Check, Close, Loading } from '@element-plus/icons-vue'
import {useExampleStore} from "@/stores/exampleStore.js";
const { proxy } = getCurrentInstance()
// 新增状态列表
const statusList = ['在线', '离线', '使用中', '维护中']
// 定义机房列表（用于下拉框）
const labList = ref([]);
const clientsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    labId: null,
    clientName: null,
    ipAddress: null,
    macAddress: null,
    status: null,
    lastHeartbeat: null,
    registrationTime: null
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    labId: [
      { required: true, message: "所属机房ID不能为空", trigger: "change" }
    ],
    clientName: [
      { required: true, message: "客户端名称 (如：PC - 01)不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态: 在线, 离线, 使用中, 维护中不能为空", trigger: "change" }
    ],
    registrationTime: [
      { required: true, message: "注册时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询客户端管理列表 */
/** 查询客户端管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.schoolId = useExampleStore().school;
  listClients(queryParams.value).then(response => {
    // 直接使用返回数据中的labs信息（不再需要从labList中查找）
    clientsList.value = response.rows.map(client => ({
      ...client,
      labName: client.labs?.labName || '未分配机房'
    }));
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error("获取列表失败：", error);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 修改重置函数，初始化状态
function reset() {
  form.value = {
    clientId: null,
    schoolId: useExampleStore().school,
    labId: null,
    clientName: null,
    ipAddress: null,
    macAddress: null,
    status: null, // 初始化状态
    lastHeartbeat: null,
    registrationTime: null
  }
  proxy.resetForm("clientsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.clientId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加客户端管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _clientId = row.clientId || ids.value
  getClients(_clientId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改客户端管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["clientsRef"].validate(valid => {
    if (valid) {
      if (form.value.clientId != null) {
        updateClients(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClients(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _clientIds = row.clientId || ids.value
  proxy.$modal.confirm('是否确认删除客户端管理编号为"' + _clientIds + '"的数据项？').then(function() {
    return delClients(_clientIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/clients/export', {
    ...queryParams.value
  }, `clients_${new Date().getTime()}.xlsx`)
}

// 修改onMounted，添加获取机房列表逻辑
// 修改onMounted中的机房列表获取逻辑
onMounted(() => {
  getList();
  // 获取当前学校的机房列表（过滤去重）
  listLabs({ schoolId: useExampleStore().school }).then(response => {
    // 使用reduce进行去重，保留唯一labId的记录
    labList.value = response.rows.reduce((acc, current) => {
      const exists = acc.some(item => item.labId === current.labId);
      if (!exists) {
        acc.push(current);
      }
      return acc;
    }, []);
  }).catch(error => {
    console.error("获取机房列表失败：", error);
  });
});
</script>
